<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 11:29
 */

namespace app\api\controller;


use app\common\controller\Api;
use think\Db;

class Comment extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    //评论列表
    public function commentList(){
        $goods_id = input('post.goods_id');
        $number   = input('post.number');
        $page     = input('post.page');
        if (!$goods_id){
            $this->error('goods_id不能为空');
        }
        if (!empty($number)){
            $this->error('参数number不能为空');
        }
        if (!empty($page)){
            $this->error('参数page不能为空');
        }
        $data['total'] = Db::name('goods_comment')->where('goods_id',$goods_id)->count();
        $data['good'] = Db::name('goods_comment')->where('goods_id',$goods_id)->where('status',0)->count();
        $data['commonly'] = Db::name('goods_comment')->where('goods_id',$goods_id)->where('status',1)->count();
        $data['wrong'] = Db::name('goods_comment')->where('goods_id',$goods_id)->where('status',2)->count();
        $data['list'] = Db::name('goods_comment')->where('goods_id',$goods_id)->limit(($page - 1) * $number,$number)->select();
        if (!$data['list']){
            $this->error('无数据');
        }
        foreach ($data['list'] as $k=>$v){
            $data['list'][$k]['member'] = Db::name('member_user')->where('id',$v['user_id'])->find();
            $data['list'][$k]['images'] = explode(',',$data['list'][$k]['images']);
            for ($i = 0 ;$i < count($data['list'][$k]['images']);$i++){
                $data['list'][$k]['images'][$i] = $this->url.$data['list'][$k]['images'][$i];
            }
        }
        $this->success('请求成功',$data);
    }
    //新增评论
    public function commentAdd(){
        $user_id = input('post.user_id');
        $goods_id   = input('post.goods_id');
        $grade   = input('post.grade');
        $comment = input('post.comment');
        $files   = request()->file('image');
        $url = $this->upload($files);
        if (!empty($url)){
            $this->error('图片上传失败');
        }
        $data = [
            'user_id'=>$user_id,
            'goods_id'=>$goods_id,
            'grade'=>$grade,
            'comment'=>$comment,
            'images'=>implode(",", $url)
        ];
        $ret = Db::name('goods_comment')->insert($data);
        if (!$ret){
            $this->error('请求失败');
        }
        $this->success('请求成功');
    }


    public function upload($files){
        // 获取表单上传文件
//        $files = request()->file('image');
        $data =[];
        foreach($files as $file){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $data[]=$info->getExtension();
            }else{

            }
        }
        return $data;
    }

}